package com.ylxl.common.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ylxl.common.result.LoginUser;
import com.ylxl.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Optional;

/**
 * @Author: Gilbert
 * @Date: 2022/7/3 21:18
 * @Description:默认插入的时候保存创建时间
 */
@Component
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {

        @Override
        public void insertFill(MetaObject metaObject) {
            this.setFieldValByName("createTime", new Date(), metaObject);
            this.strictInsertFill(metaObject,"createBy", String.class, Optional.ofNullable(SecurityUtils.getLoginUser()).isPresent() ? SecurityUtils.getLoginUser().getUsername() : "admin" );
            this.setFieldValByName("updateTime", new Date(), metaObject);
        }
        @Override
        public void updateFill(MetaObject metaObject) {
            this.setFieldValByName("updateTime", new Date(),metaObject);
            this.strictUpdateFill(metaObject, "updateBy", String.class,Optional.ofNullable(SecurityUtils.getLoginUser()).isPresent() ? SecurityUtils.getLoginUser().getUsername() : "admin");
        }
}
